/**
 * 定义链表类
 * @param {*} val
 * @param {ListNode} next
 */
function ListNode(val, next=null) {
  this.val = val;
  this.next = next;
}

/**
 * 数组转换链表
 * @param {Array} arr
 * @return {ListNode}
 */
const getListNodeFromArray = (arr) => {
  let ln = new ListNode()
  let pre = ln
  arr && arr.forEach(v => pre = pre.next = new ListNode(v))
  return ln.next;
}

/**
 * 链表转换数组
 * @param {ListNode} ln
 * @return {Array}
 */
const getArrayFromListNode = (ln) => {
  let arr = [];
  while (ln) {
    arr.push(ln.val)
    ln = ln.next
  }
  return arr;
}

/**
 * 翻转单链表
 * @param {ListNode} ln
 * @return {ListNode}
 */
const reverseLn = (ln) => {
  let cur = ln
  let pre = null
  while (cur) {
    let temp = cur.next
    cur.next = pre
    pre = cur
    cur = temp
  }
  return pre
}


/**
 * 打印链表
 * @param {ListNode} ln
 */
const logList = (ln) => {
  let str = ""
  while (ln) {
    str = `${str}${str && '->'}${ln.val}`
    ln = ln.next
  }
  console.log("listnode: ", str);
}

module.exports = {ListNode, getListNodeFromArray, getArrayFromListNode, logList, reverseLn}